package com.lh_travel.lohas.activity.user;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lh_travel.lohas.R;
import com.lh_travel.lohas.adapter.DoubleViewRecylerAdapter;
import com.lh_travel.lohas.base.api;
import com.lh_travel.lohas.base.baseActivity;
import com.lh_travel.lohas.domain.DafultMessageEvent;
import com.lh_travel.lohas.domain.MutilBean;
import com.lh_travel.lohas.domain.UserBean;
import com.lh_travel.lohas.domain.respon;
import com.lh_travel.lohas.utils.Preferences;
import com.tamic.novate.Throwable;
import com.tamic.novate.callback.RxResultCallback;
import com.tamic.novate.callback.RxStringCallback;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.ListIterator;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;

public class AccountActivity extends baseActivity {

    private Toolbar toolbar;
    private ImageButton img_back;
    private SwipeMenuRecyclerView rcy;
    private Button btn_confirm;
    private ArrayList<MutilBean> datalist;
    private UserBean userBean;
    private DoubleViewRecylerAdapter doubleadapter;
    private RelativeLayout rl_bind;
    private myCountTimer timer;
    private RelativeLayout rl_info;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_accountbind);

        findView();
        bindListner();
        ensureUI();
    }

    @Override
    public void findView() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        img_back = (ImageButton) findViewById(R.id.img_back);
        rcy = (SwipeMenuRecyclerView) findViewById(R.id.rcy);
        btn_confirm = (Button) findViewById(R.id.btn_confirm);
        rl_bind = (RelativeLayout) findViewById(R.id.rl_bind);
        rl_info = (RelativeLayout) findViewById(R.id.rl_info);
    }

    @Override
    public void bindListner() {
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        btn_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mApp.setBeanPrefernce(Preferences.LOCAL.USERLOGIN, null);

                DafultMessageEvent event = new DafultMessageEvent();
                event.TAG = "LoginActivity";

                EventBus.getDefault().post(event);

                finish();
            }
        });

        rl_bind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                showDialog();

            }
        });

        rl_info.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(mContext, UserInfoActivity.class);

                startActivity(intent);

            }
        });
    }

    private void showDialog() {

        View view = LayoutInflater.from(mContext).inflate(R.layout.my_dialog, null);
        final AlertDialog mDialog = new AlertDialog.Builder(mContext)
                .setView(view).create();

        mDialog.setCancelable(false);

        final EditText ed_tel = (EditText) view.findViewById(R.id.ed_tel);
        final EditText ed_pwd = (EditText) view.findViewById(R.id.ed_pwd);

        final Button btn_send = view.findViewById(R.id.btn_send);

        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (ed_tel.getText().toString().trim().length() < 11) {

                    showMessage("请输入正确的手机号");

                } else {

                    new api(mContext).sendCode(ed_tel.getText().toString().trim(), "login", new RxStringCallback() {
                        @Override
                        public void onNext(Object tag, String response) {
                            respon result = new Gson().fromJson(response, new TypeToken<respon>() {
                            }.getType());

                            if (result.code.equals("200")) {

                                timer = new myCountTimer(60000, 1000, btn_send);
                                timer.start();

                                showMessage("验证码以发送到您手机上");

                            } else {

                                showMessage("失败");

                            }
                        }

                        @Override
                        public void onError(Object tag, Throwable e) {

                        }

                        @Override
                        public void onCancel(Object tag, Throwable e) {

                        }
                    });
                }
            }
        });


        view.findViewById(R.id.ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final String number = ed_tel.getText().toString().trim();
                String pwd = ed_pwd.getText().toString().trim();

                if (ed_tel.getText().toString().trim().length() < 11) {

                    showMessage("请输入正确的手机号");

                } else if (ed_pwd.getText().toString().trim().length() == 0) {

                    showMessage("请输入正确的验证码");

                } else {

                    showViewLoad();

                    new api(mContext).updatePhone(number, pwd, userBean.token, new RxStringCallback() {
                        @Override
                        public void onNext(Object tag, String response) {

                            respon result = new Gson().fromJson(response, new TypeToken<respon>() {
                            }.getType());

                            if (result.code.equals("200")) {

                                //修改成功
                                userBean.phone = number;
                                mDialog.dismiss();
                            }

                            showMessage(result.message);
                            dismissViewLoad();
                        }

                        @Override
                        public void onError(Object tag, Throwable e) {
                            dismissViewLoad();
                        }

                        @Override
                        public void onCancel(Object tag, Throwable e) {
                            dismissViewLoad();
                        }
                    });
                }
            }
        });

        view.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                mDialog.dismiss();
            }
        });
        mDialog.show();
    }


    @Override
    public void ensureUI() {
        setSupportActionBar(toolbar);
        toolbar.setEnabled(true);

        HashMap<Integer, Integer> map = new HashMap<>();

        map.put(1, R.layout.item_city);
        map.put(2, R.layout.item_accountbind);

        userBean = mApp.getBeanPrefernce(Preferences.LOCAL.USERLOGIN);

        datalist = new ArrayList<>();

        /*datalist.add(new MutilBean("安全绑定", 0, 1, false));
        datalist.add(new MutilBean("手机号", R.drawable.phone, 2, userBean.phone.length() > 0 ? true : false));*/
        datalist.add(new MutilBean("第三方账号绑定", 0, 1, false));
        datalist.add(new MutilBean("QQ", R.drawable.qqc, 2, userBean.qq_avatar.length() > 0 ? true : false));
        datalist.add(new MutilBean("微信", R.drawable.wec, 2, userBean.wx_avatar.length() > 0 ? true : false));

        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);

        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rcy.setLayoutManager(layoutManager);

        doubleadapter = new DoubleViewRecylerAdapter<MutilBean>(datalist, map) {

            @Override
            public void convertTo(BaseViewHolder baseViewHolder, final MutilBean item) {

                switch (baseViewHolder.getItemViewType()) {

                    case 1:

                        baseViewHolder.setText(R.id.tv_name, item.name);
                        baseViewHolder.setBackgroundColor(R.id.rl_main, Color.TRANSPARENT);

                        break;

                    case 2:

                        baseViewHolder.setText(R.id.tv_title, item.name);
                        baseViewHolder.setImageDrawable(R.id.img_pic, mContext.getDrawable(item.pic));
                        baseViewHolder.setText(R.id.btn_bind, item.bind ? "解绑" : "绑定");
                        break;

                }
            }
        };

        doubleadapter.setOnRecyclerViewItemClickListener(new BaseQuickAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int i) {
                switch (i) {

                    case 1:

                        showViewLoad();
                        if (datalist.get(i).bind) {

                            //解绑
                            new api(mContext).unBindThird(userBean.qq_uuid, "1", userBean.token, new RxStringCallback() {
                                @Override
                                public void onNext(Object tag, String response) {
                                    respon result = new Gson().fromJson(response, new TypeToken<respon>() {
                                    }.getType());

                                    if (result.code.equals("200")) {
                                        //解绑成功
                                        userBean.qq_avatar = "";
                                        userBean.qq_nick = "";
                                        userBean.qq_uuid = "";

                                        mApp.setPreference(Preferences.LOCAL.LOGINTYPE, "1");

                                        DafultMessageEvent event = new DafultMessageEvent();
                                        event.TAG = "LoginActivity";

                                        EventBus.getDefault().post(event);

                                        dismissViewLoad();

                                        arrNotify(1, false);

                                        doubleadapter.notifyDataSetChanged();
                                    }
                                }

                                @Override
                                public void onError(Object tag, Throwable e) {
                                    dismissViewLoad();
                                }

                                @Override
                                public void onCancel(Object tag, Throwable e) {
                                    dismissViewLoad();
                                }
                            });

                        } else {

                            login_third(QQ.NAME, "1");
                        }

                        break;

                    case 2:

                        showViewLoad();
                        if (datalist.get(i).bind) {

                            //解绑
                            new api(mContext).unBindThird(userBean.qq_uuid, "1", userBean.token, new RxStringCallback() {
                                @Override
                                public void onNext(Object tag, String response) {
                                    respon result = new Gson().fromJson(response, new TypeToken<respon>() {
                                    }.getType());

                                    if (result.code.equals("200")) {
                                        //解绑成功
                                        userBean.qq_avatar = "";
                                        userBean.qq_nick = "";
                                        userBean.qq_uuid = "";

                                        mApp.setPreference(Preferences.LOCAL.LOGINTYPE, "1");

                                        DafultMessageEvent event = new DafultMessageEvent();
                                        event.TAG = "LoginActivity";

                                        EventBus.getDefault().post(event);

                                        dismissViewLoad();
                                    }
                                }

                                @Override
                                public void onError(Object tag, Throwable e) {
                                    dismissViewLoad();
                                }

                                @Override
                                public void onCancel(Object tag, Throwable e) {
                                    dismissViewLoad();
                                }
                            });

                        } else {

                            login_third(Wechat.NAME, "2");
                        }

                        break;

                }
            }
        });

        rcy.setAdapter(doubleadapter);

    }

    private void arrNotify(int position, boolean bind){

        datalist.get(position).bind = bind;

    }

    private void login_third(String name, final String type) {
        Platform plat = ShareSDK.getPlatform(name);
        plat.removeAccount(true); //移除授权状态和本地缓存，下次授权会重新授权
        plat.SSOSetting(false); //SSO授权，传false默认是客户端授权，没有客户端授权或者不支持客户端授权会跳web授权
        plat.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(final Platform platform, int i, HashMap<String, Object> hashMap) {

                //绑定 需要第三方登录
                new api(mContext).bindThird(userBean.qq_uuid, type, type.equals("1") ? userBean.qq_nick : userBean.wx_nick, type.equals("1") ? userBean.qq_avatar : userBean.wx_avatar,
                        userBean.token, new RxResultCallback<UserBean>() {
                            @Override
                            public void onNext(Object tag, int code, String message, UserBean response) {

                                if (code == 200) {

                                    mApp.setBeanPrefernce(Preferences.LOCAL.USERLOGIN, response);
                                    DafultMessageEvent event = new DafultMessageEvent();
                                    event.TAG = "LoginActivity";

                                    EventBus.getDefault().post(event);

                                    dismissViewLoad();

                                    arrNotify(Integer.parseInt(type), true);

                                    doubleadapter.notifyDataSetChanged();
                                }

                            }

                            @Override
                            public void onError(Object tag, Throwable e) {
                                dismissViewLoad();
                            }

                            @Override
                            public void onCancel(Object tag, Throwable e) {
                                dismissViewLoad();
                            }
                        });

            }

            @Override
            public void onError(Platform platform, int i, java.lang.Throwable throwable) {

                showMessage("发生未知错误");
                dismissViewLoad();

            }

            @Override
            public void onCancel(Platform platform, int i) {

                showMessage("取消第三方登录");
                dismissViewLoad();

            }
        });

        plat.showUser(null);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (timer != null) {
            timer.cancel();
        }
    }

    private static class myCountTimer extends CountDownTimer {

        private Button btn;

        public myCountTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        public myCountTimer(long millisInFuture, long countDownInterval, Button btn) {
            super(millisInFuture, countDownInterval);
            this.btn = btn;
        }

        @Override
        public void onTick(long millisUntilFinished) {
            btn.setEnabled(false);
            btn.setText(millisUntilFinished / 1000 + "秒后可重发");

        }

        @Override
        public void onFinish() {
            btn.setEnabled(true);
            btn.setText("发送验证码");
        }
    }
}
